package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 定时任务测试
 *
 * @Author iPan
 * @Date 2025/7/8
 */
@Component
public class Sample3 {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @XxlJob("sleepTest")
    public void sleepTest() throws Exception {
        System.out.println("sleepTest begin"); // 本地打印
        logger.info("sleepTest log begin"); // 本地打印

        long jobId = XxlJobHelper.getJobId(); // 当前任务ID
        String jobParam = XxlJobHelper.getJobParam(); // 任务调度入参
        String logFileName = XxlJobHelper.getJobLogFileName(); // 日志保存路径
        int shardIndex = XxlJobHelper.getShardIndex(); // 获取分片序号（如果有分片任务）
        int shardTotal = XxlJobHelper.getShardTotal(); // 获取分片总数（如果有分片任务）

        XxlJobHelper.log("XxlJobHelper.log begin"); // 调度器侧打印
        XxlJobHelper.log("XxlJobHelper.log jobId={}, jobParam={}, logFileName={}, shardIndex={}, shardTotal={}",
                jobId, jobParam, logFileName, shardIndex, shardTotal);
        TimeUnit.SECONDS.sleep(10);
        XxlJobHelper.handleSuccess("任务执行成功"); // 调度器打印
        System.out.println("sleepTest end");
        logger.info("sleepTest log end");
    }

    @XxlJob("exceptionTest")
    public void exceptionTest() throws Exception {
        System.out.println("exceptionTest begin"); // 本地打印
        XxlJobHelper.log("out: exceptionTest begin");

        try {
            TimeUnit.SECONDS.sleep(60);
        } catch (InterruptedException e) {
            //System.out.println("中断异常"); // 捕获：后面队列里的任务还会继续被执行、整个任务并没有被终止；
            throw e; // 不捕获：后面队列里的任务还会继续被执行、整个任务并没有被终止；
            // 文档说是要终止线程，必须抛出InterruptedException异常；实际上，抛出InterruptedException异常是可以终止当前任务，但队列里面的任务并没有清除！
        }

        System.out.println("exceptionTest end");
        XxlJobHelper.log("out: exceptionTest end");
    }

}
